<?php
class Filemanager extends CI_Controller {
	private $error = array();
	
	public function index() {
		$this->data['title'] = '图档管理';
		
		$this->data['base'] = base_url();
		
		$this->data['entry_folder'] = '新建文件夹';
		$this->data['entry_move'] = '移动';
		$this->data['entry_copy'] = '复制';
		$this->data['entry_rename'] = '重命名';
		
		$this->data['button_folder'] = '新建文件夹';
		$this->data['button_delete'] = '删除';
		$this->data['button_move'] = '移动';
		$this->data['button_copy'] = '复制';
		$this->data['button_rename'] = '重命名';
		$this->data['button_upload'] = '上传';
		$this->data['button_refresh'] = '刷新'; 
		
		$this->data['error_select'] = '警告：请选择一个目录或文件';
		$this->data['error_directory'] = '警告：请选择一个目录';
				
		$this->data['directory'] = HTTP_IMAGE . 'data/';
		
		if ($this->input->get('field')) {
			$this->data['field'] = $this->input->get('field');
		} else {
			$this->data['field'] = '';
		}
		
		if ($this->input->get('CKEditorFuncNum')) {
			$this->data['fckeditor_function'] = $this->input->get('CKEditorFuncNum');
			$this->data['fckeditor'] = TRUE;
		} else {
			$this->data['fckeditor_function'] = 0;
			$this->data['fckeditor'] = FALSE;
		}
		
		$this->load->view('common/filemanager.tpl',$this->data);	
	}	
	
	public function image() {
		$this->load->model('toolimage_model');
		
		if ($this->input->post('image')) {
			if($this->input->post('tool')){
				echo HTTP_IMAGE . $this->input->post('image');
			}else{
				echo $this->toolimage_model->resize($this->input->post('image'), 100, 100);
			}
		}
	}
	
	public function directory() {	
		$json = array();
		
		$directories = glob(rtrim(DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('directory')), '/') . '/*', GLOB_ONLYDIR); 
		
		if ($directories) {
			$i = 0;
		
			foreach ($directories as $directory) {
				$json[$i]['data'] = basename($directory);
				$json[$i]['attributes']['directory'] = substr($directory, strlen(DIR_IMAGE . 'data/'));
				
				$children = glob(rtrim($directory, '/') . '/*', GLOB_ONLYDIR);
				
				if ($children)  {
					$json[$i]['children'] = ' ';
				}
				
				$i++;
			}
		}		
		echo json_encode($json);exit;	
		
	}
	
	public function files() {
		$json = array();
		
		$this->load->model('toolimage_model');
		
		if ($this->input->post('directory') && $this->input->post('directory')) {
			$directory = DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('directory'));
		} else {
			$directory = DIR_IMAGE . 'data/';
		}
		
		$allowed = array(
			'.jpg',
			'.jpeg',
			'.png',
			'.gif'
		);
		
		$files = glob(rtrim($directory, '/') . '/*');
		
		foreach ($files as $file) {
			if (is_file($file)) {
				$ext = strrchr($file, '.');
			} else {
				$ext = '';
			}	
			
			if (in_array(strtolower($ext), $allowed)) {
				$size = filesize($file);
	
				$i = 0;
	
				$suffix = array(
					'B',
					'KB',
					'MB',
					'GB',
					'TB',
					'PB',
					'EB',
					'ZB',
					'YB'
				);
	
				while (($size / 1024) > 1) {
					$size = $size / 1024;
					$i++;
				}
					
				$json[] = array(
					'file'     => substr($file, strlen(DIR_IMAGE . 'data/')),
					'filename' => basename($file),
					'size'     => round(substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i],
					'thumb'    => $this->toolimage_model->resize(substr($file, strlen(DIR_IMAGE)), 100, 100)
				);
			}
		}
		
		echo json_encode($json);exit;	
	}	
	
	public function create() {
				
		$json = array();
		
		if ($this->input->post('name') || $this->input->post('name')) {
			$directory = rtrim(DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('directory')), '/');							   
			if (!is_dir($directory)) {
				$json['error'] = '警告：请选择一个目录a ';
				$json['t'] = $directory;
			}
			
			if (file_exists($directory . '/' . str_replace('../', '', $this->input->post('name')))) {
				$json['error'] = '警告：文件名或目录名已存在';
			}
		} else {
			$json['error'] = '警告：请输入一个新名称';
		}
		
		/*
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
      		$json['error'] = $this->language->get('error_permission');  
    	}
		*/
		
		if (!isset($json['error'])) {	
			mkdir($directory . '/' . str_replace('../', '', $this->input->post('name')), 0777);
			
			$json['success'] = '成功：新建目录';
		}	
		
		echo json_encode($json);exit;	

	}
	
	public function delete() {
		
		$json = array();
		
		if ($this->input->post('path')) {
			$path = rtrim(DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('path')), '/');
			 
			if (!file_exists($path)) {
				$json['error'] = '警告：请选择一个目录或文件';
			}
			
			if ($path == rtrim(DIR_IMAGE . 'data/', '/')) {
				$json['error'] = '警告：您不能删除此目录';
			}
		} else {
			$json['error'] = '警告：请选择一个目录或文件';
		}
		/*
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
      		$json['error'] = $this->language->get('error_permission');  
    	}
		*/
		
		if (!isset($json['error'])) {
			if (is_file($path)) {
				unlink($path);
			} elseif (is_dir($path)) {
				$this->recursiveDelete($path);
			}
			
			$json['success'] = '成功：文件或目录已被删除';
		}				
		
		echo json_encode($json);exit;	

	}

	protected function recursiveDelete($directory) {
		if (is_dir($directory)) {
			$handle = opendir($directory);
		}
		
		if (!$handle) {
			return FALSE;
		}
		
		while (false !== ($file = readdir($handle))) {
			if ($file != '.' && $file != '..') {
				if (!is_dir($directory . '/' . $file)) {
					unlink($directory . '/' . $file);
				} else {
					$this->recursiveDelete($directory . '/' . $file);
				}
			}
		}
		
		closedir($handle);
		
		rmdir($directory);
		
		return TRUE;
	}

	public function move() {
	
		$json = array();
		
		if ($this->input->post('from') && $this->input->post('to') ) {
			$from = rtrim(DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('from')), '/');
			
			if (!file_exists($from)) {
				$json['error'] = '警告：文件或目录不存在!';
			}
			
			if ($from == DIR_IMAGE . 'data') {
				$json['error'] = '警告：不能更改主目录!';
			}
			
			$to = rtrim(DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('to')), '/');

			if (!file_exists($to)) {
				$json['error'] = '警告：移动至目录不存在!';
			}	
			
			if (file_exists($to . '/' . basename($from))) {
				$json['error'] = '警告：文件名或目录名已存在!';
			}
		} else {
			$json['error'] = '警告：请选择一个目录!';
		}
		
		/*
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
      		$json['error'] = $this->language->get('error_permission');  
    	}
		*/
		
		if (!isset($json['error'])) {
			rename($from, $to . '/' . basename($from));
			
			$json['success'] = '成功：文件或目录已被移动!';
		}
		
		echo json_encode($json);exit;	

	}	
	
	public function copy() {
	
		$json = array();
		
		if ($this->input->post('path') && $this->input->post('name')) {
			if ((strlen(utf8_decode($this->input->post('name'))) < 3) || (strlen(utf8_decode($this->input->post('name'))) > 255)) {
				$json['error'] = '警告：文件名必须在3至255个字之间';
			}
				
			$old_name = rtrim(DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('path')), '/');
			
			if (!file_exists($old_name) || $old_name == DIR_IMAGE . 'data') {
				$json['error'] = '警告：无法复制这个文件或目录!';
			}
			
			if (is_file($old_name)) {
				$ext = strrchr($old_name, '.');
			} else {
				$ext = '';
			}		
			
			$new_name = dirname($old_name) . '/' . str_replace('../', '', $this->input->post('name') . $ext);
																			   
			if (file_exists($new_name)) {
				$json['error'] = '警告：文件名或目录名已存在!';
			}			
		} else {
			$json['error'] = '警告：请选择一个目录或文件!';
		}
		/*
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
      		$json['error'] = $this->language->get('error_permission');  
    	}
		*/
		
		if (!isset($json['error'])) {
			if (is_file($old_name)) {
				copy($old_name, $new_name);
			} else {
				$this->recursiveCopy($old_name, $new_name);
			}
			
			$json['success'] = '成功：文件或目录已被复制!';
		}
		
		echo json_encode($json);exit;	

	}

	function recursiveCopy($source, $destination) { 
		$directory = opendir($source); 
		
		@mkdir($destination); 
		
		while (false !== ($file = readdir($handle))) {
			if (($file != '.') && ($file != '..')) { 
				if (is_dir($source . '/' . $file)) { 
					$this->recursiveCopy($source . '/' . $file, $destination . '/' . $file); 
				} else { 
					copy($source . '/' . $file, $destination . '/' . $file); 
				} 
			} 
		} 
		
		closedir($directory); 
	} 

	public function folders() {
		echo $this->recursiveFolders(DIR_IMAGE . 'data/');
	}
	
	protected function recursiveFolders($directory) {
		$output = '';
		
		$output .= '<option value="' . substr($directory, strlen(DIR_IMAGE . 'data/')) . '">' . substr($directory, strlen(DIR_IMAGE . 'data/')) . '</option>';
		
		$directories = glob(rtrim(str_replace('../', '', $directory), '/') . '/*', GLOB_ONLYDIR);
		
		foreach ($directories  as $directory) {
			$output .= $this->recursiveFolders($directory);
		}
		
		return $output;
	}
	
	public function rename() {
	
		$json = array();
		
		if ($this->input->post('path') && $this->input->post('name')) {
			if ((strlen(utf8_decode($this->input->post('name'))) < 3) || (strlen(utf8_decode($this->input->post('name'))) > 255)) {
				$json['error'] = '警告：文件名必须在3至255个字之间!';
			}
				
			$old_name = rtrim(DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('path')), '/');
			
			if (!file_exists($old_name) || $old_name == DIR_IMAGE . 'data') {
				$json['error'] = '警告：不能重命名此目录';
			}
			
			if (is_file($old_name)) {
				$ext = strrchr($old_name, '.');
			} else {
				$ext = '';
			}		
			
			$new_name = dirname($old_name) . '/' . str_replace('../', '', $this->input->post('name') . $ext);
																			   
			if (file_exists($new_name)) {
				$json['error'] = '警告：文件名或目录名已存在';
			}			
		}
		/*
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
      		$json['error'] = $this->language->get('error_permission');  
    	}
		*/
		
		if (!isset($json['error'])) {
			rename($old_name, $new_name);
			
			$json['success'] = '成功：文件或目录已被重命名!';
		}
		echo json_encode($json);exit;	

	}
	
	public function upload() {
	
		$json = array();
		
		if (isset($_FILES['image']) && $_FILES['image']['tmp_name']) {
			if ((strlen(utf8_decode($_FILES['image']['name'])) < 3) || (strlen(utf8_decode($_FILES['image']['name'])) > 255)) {
				$json['error'] = '警告：文件名必须在3至255个字之间';
			}
				
			$directory = rtrim(DIR_IMAGE . 'data/' . str_replace('../', '', $this->input->post('directory')), '/');
			
			if (!is_dir($directory)) {
				$json['error'] = '警告：请选择一个目录';
			}
			
			if ($_FILES['image']['size'] > 3145728) {
				$json['error'] = '警告：图片文件太大，请保持文件不大于3M，且尺寸不得大于1000px X 1000px!';
			}
			
			$allowed = array(
				'image/jpeg',
				'image/pjpeg',
				'image/png',
				'image/x-png',
				'image/gif',
				'application/x-shockwave-flash'
			);
					
			if (!in_array($_FILES['image']['type'], $allowed)) {
				$json['error'] = '警告：不正确的文件类型';
			}
			
			$allowed = array(
				'.jpg',
				'.jpeg',
				'.gif',
				'.png',
				'.flv'
			);
					
			if (!in_array(strtolower(strrchr($_FILES['image']['name'], '.')), $allowed)) {
				$json['error'] = '警告：不正确的文件类型';
			}

			
			if ($_FILES['image']['error'] != UPLOAD_ERR_OK) {
				$json['error'] = 'error_upload_' . $_FILES['image']['error'];
			}			
		} else {
			$json['error'] = '警告：请选择一个文件!';
		}
	
		/*
		if (!$this->user->hasPermission('modify', 'common/filemanager')) {
      		$json['error'] = $this->language->get('error_permission');  
    	}
		*/
		
		if (!isset($json['error'])) {	
			if (@move_uploaded_file($_FILES['image']['tmp_name'], $directory . '/' . basename($_FILES['image']['name']))) {		
				$json['success'] = '成功：您的文件已上传!';
			} else {
				$json['error'] = '警告：原因不明，文件不能上传!';
			}
		}
		
		echo json_encode($json);exit;	

	}
} 
?>